\chapter{Model-View-Controller}
No matter it is a small program, such as an Internet browser or a calculator, or it is an enterprise-level application, like computer-aided design (CAD) or the complex data warehouse, the Graphical User Interface (GUI) is always the most front end which interacts with users. Therefore, the quality of GUI directly influences the user experience and the usability of the software. As the users request the easier-and-easier-to-use applications and the software engineers pay more and more attention on it, the study on how to systematically design and develop the satisfying GUI becomes a serious theory. When people started to develop GUI in the real life, they found out that the GUI development just caused the same set of problems with the ones they encountered in their system development. As a matter of fact, just because of the similarity, several different but similar solutions were come up with. Model-View-Controller (MVC) \citep{Wikipedia2007} was one of them.

\section{Old UI Architecture}
In the early time of software development, although the software engineers and developers supplied many very nice GUI architectures, from the development perspective some of these architectures actually had lots of problems which would potentially result in some issues, e.g. maintenance, unit-testing and reusability, for the further development. Microsoft was one of the creators of these GUI architectures. It indeed brought the UI revolution into the industry in the year of 1990 when Windows version 3.0 was released. Since then it has strongly influenced the direction of the GUI development.  Even until now, some of the original ideas still work in some of the undergoing projects. 

\subsection{Forms and Controls}
\begin{figure}
	\centering
		\includegraphics[width=0.7\textwidth]{../pic/dmvapplet.jpg}
		\caption{An Example of Old UI Architecture (Source: www.diamondedge.com)} 
	\label{fig:dmvapplet}
\end{figure}

Figure \ref{fig:dmvapplet} is a typical UI architecture of Windows style. Martin Fowler \footnote{Martin Fowler is a famous author and international speaker on software architecture. His website is http://martinfowler.com/} called it \textit{Forms and Controls}. It presents a form composed with many labels, text fields and buttons, which directly expose the two most essential concepts of this architecture, i.e. the form and the control. 

The form is specific to the window. It is the container of all the controls. Usually the form takes care of two tasks:
\begin{description}
	\item [Screen layout]: Usually there is always a layout manager, which controls the arrangement of the controls. Different layout manager may arrange controls by different means. Some of them position controls by coordinates or offsets. Some of them just stack the controls in single direction. In addition to this, the form should also construct the hierarchic structure for controls working with each other. 
	\item	[Form logic]: It is the behavior between controls. A control usually needs to work with other controls to finish a task. This action happens out of any control. Therefore, it cannot be easily programmed into the control themselves. Instead, it should be defined in the scope of the form.
\end{description}

The control can be taken as the smallest interactive unit with users. A control can have several states. However, simply speaking, these states can be divided into two general states, i.e. Enabled and Disabled states. An enabled control means it is ready to work. In this state, basically it is responsible for two interactions.

One of the interactions is to listen to the registered events and call the corresponding functions: Events are always the ones which directly talk with controls. There are all kinds of events that can take place when an application is running, e.g. when a user click on a button, the \textit{ButtonClick} event is triggered, or when a system alarm alerts, the \textit{AlarmAlert} event happens. Generally they are system events and user input events. They are just so many that the controls should be aware of them before they are able to forward the messages to the responsible functions, which are usually called \textit{Enventhandlers}. Therefore, controls need to register the events that they can handle. Each of controls keeps a dictionary of the events that it has to deal with, and for each of the events the control has to specify a responsible event handler. After the registration, the control starts to listen. Whenever the control captures an incoming event, it will look the event up in his dictionary. If the control can find it, it will call the specified event handler to handle the event. Otherwise the control will just ignore it. Figure \ref{fig:eventhandling} illustrates how a control handles events, and Listing \ref{lst:alarmevent} shows how to implement an event and its event handler for a control class by C\# programming language.

\begin{figure}
	\centering
		\includegraphics[width=0.7\textwidth]{../pic/eventhandling.jpg}
	\caption{How A Control Handles Events (Source:\cite{Johnson1999})}
	\label{fig:eventhandling}
\end{figure}
 
\lstset{language=c++}
\lstset{backgroundcolor=\color{listinggray}}
\lstset{linewidth=\linewidth}
\lstset{columns=flexible}
%\lstset{numbers=left}
\begin{lstlisting}[frame=tb,caption=The C\# Implementation of The Alarm Event (Source: \cite{MSDN}),label=lst:alarmevent]{}
// Define the data for the event class
public class AlarmEventArgs : EventArgs
{ ... }

// Declare the responsible event handler
public delegate void AlarmEventHandler(object sender, AlarmEventArgs e);

// Define the control class
public class AlarmClock
{
  // register the Alarm event by defining its type as AlarmEventHandler
  public event AlarmEventHandler Alarm;
  
  // raise the event when the alarm is triggered
  protected virtual void OnAlarm(AlarmEventArgs e)
  { ... }  
}
\end{lstlisting}

The other one is to display data. Some controls, like label, don't really need to take any input from users in the run time. Instead, they display data for the users. This is a kind of one-way interaction. The displayed data can be various. They can be some informational texts, e.g. the notes in a form, or they can be the result of some calculation, e.g. the outcome of the currency converter, or they can be the state of some undergoing progress, e.g. the temperature of the refrigerator. In any of these cases, the data will always come from somewhere. The most common source is the database. 

However, considering the performance and data's integrity, in the real applications most of time there are three copies of the data involved:
\begin{itemize}
	\item One copy of the data is the data residing in the database. This data is always stored in certain database-specific structure and managed by the hosting database server. It is the lasting record of the data, shared by multiple applications and users who have the access to it. According to Martin Fowler's terminology, it is called the \textit{record state}.
	\item Another copy is kept inside in-memory Records-Sets within the application. As for the concrete location, it depends on the type of the application. Most of the web applications request the client machine to provide the certain temporary area to save the data relevant to current communications between the application and database. In Internet terminology, this is usually what the \textit{cookie} \citep{Wikipedia2007b} refers to. However, there is no such area in desktop applications. Instead, the hosting machine allocates some part of the main memory (RAM) for the desktop application to store the data just in the run-time. Martin Fowler called this copy of data the \textit{session state}.
	\item The final copy of data lies in the GUI components themselves. This is the data that the users can directly read on the screen, thus Martin Fowler named it as the \textit{screen state}. Because this data always entirely or partially comes from the in-memory copy of data, and also this data can directly update the corresponding data in memory, it is very non-trivial to keep the session state and the screen state synchronized all the time.
\end{itemize}

People want to be ensured that the data they can see from the screen is the real data the application is presenting, and also the data they input to the screen is being processed by the application at the backstage. Then the synchronization between the session state and screen state is strongly required. However, it is quite complicated mechanism, especially from the programming perspective, because there are always two parties involved and each of the party should be promised that it will be immediately updated once the linked party is changed. Things can become really messy when many UI components are involved, if there is no good mechanism to facility the synchronization. Fortunately, Data binding \citep{Jain2003} can make life easier. 

Simply speaking, data binding is a powerful feature that enables visual elements in a client to connect to a data source such as DataSets, DataViews, Arrays etc. Some of the visual elements in the client side can be TextBox, DataGrid etc. Here the visual element stores the screen state data, whereas the data source keeps the session data. Data binding can make sure that any change to either the control data, or the underlying data source was immediately propagated to the other. Therefore, for example, if the thermometer changes the in-memory data to the current temperature, the bound UI component in the front-end will be effectively updated. Similarly, if the user sets the temperature by inputting certain value, the underlying data will force the air container to adjust the environmental temperature to that value. Generally, data binding can be carried out in one way or two ways, which is totally up to the scenarios. Figure \ref{fig:binding} shows how the UI controls are data bound with the underlying data.

\begin{figure}
	\centering
		\includegraphics[width=0.7\textwidth]{../pic/binding.jpg}
	\caption{Data Binding Concept (Source: \cite{Jain2003})}
	\label{fig:binding}
\end{figure}

\subsection{Issues}

The major disadvantage of \textit{Forms and Controls} architecture is that the data and presentation are mixed together. This directly resulted in these three main issues. Firstly, since the data cannot be separated from the presentation, the developers have to consider developing the data models in the manner that the designers can possibly build the presentation on the data models. The same drawback happened to the designers as well, because they had to worry about how the data can populate into their designed presentation. They cannot independently design the presentation, and they cannot freely test the presentation either. Secondly, the mixed architecture becomes very troublesome when either the presentation or the data model needs to be changed. Any change on one side will directly cause that the other side will function incorrectly or even can not function at all. Therefore, the two parts need to be involved in the maintenance of the software. Lastly, the UI components have the least potential to be reused. Because any piece of the presentation is related to certain dataset, if this UI control needs to be applied into a new environment, the undergoing dataset in the new environment should match the requirement of the UI control, which is quite unlikely to happen. Therefore, a UI control which has the same presentation but different dataset has to be created.  

Therefore, to solve these issues, it is necessary to separate the data from the presentation \citep{Fowler2006a}. The data should be completely self-contained and work without reference to the presentation. Additionally, it should also be able to support multiple presentations, possibly simultaneously. Actually, the division of components has enormous advantages. Since the functional units are isolated from each other to the maximal extent, the designers and developers can just concentrate on their own units without the knowledge about everything in other units. Furthermore, to make the modularity even cleaner, the interactive part of the presentation can be also taken out. Then the three-way division of application can thoroughly separate the parts that represent the model of the underlying data from the way the model is presented to the user and from the way the user interacts with it. This is the origin of the idea of Model-View-Controller (MVC).

\section{MVC Pattern}

\subsection{Introduction}

Model-View-Controller (MVC) is an architectural pattern used in software engineering. In complex computer applications that present a large amount of data to the user, a developer often wishes to separate data (Model) and user interface (View), so that changes to the user interface will not affect data handling, and that the data can be reorganized without changing the user interface. The Model-View-Controller solves this problem by decoupling data access and business logic from data presentation and user interaction, by introducing an intermediate component: the Controller.

MVC is a very complex architectural pattern, and understandably it also looks very complex to implement. However, if the whole architectural pattern is analyzed from design pattern perspectives, it is not hard to find out that the combination of different design patterns can make the implementation of MVC a lot easier. \textit{View} can be seen as a tree, thus apparently it can be realized in \textit{Composition Pattern}. The relationship between \textit{View} and \textit{Model} can be expressed in \textit{Observer Pattern}. \textit{Controller} controls the representation of \textit{View}, therefore it can be implemented in \textit{Strategy Pattern}. \textit{Model} is usually a mediator, and it should be realized in \textit{Mediator Pattern}.

\subsection{Model}

Model is used to manage information and notify observers when that information changes. It contains only data and functionality that are related by a common purpose. If two groups of unrelated data and functionality are needed, two separate models should be created.

Model encapsulates more than just data and functions that operate on it. A model is meant to serve as a computational approximation or abstraction of some real world process or system. It captures not only the state of a process or system, but how the system works. This makes it very easy to use real-world modeling techniques in defining your models. For example, a model is used to bridge the computational back-end with the GUI front-end. In this scenario, the model wraps and abstracts the functionality of a computation engine or hardware system and acts as an agent requesting the real services of the system it models.

\subsection{View}

View is responsible for mapping graphics onto a device. A view typically has a one to one correspondence with a display surface and knows how to render to it. A view attaches to a model and renders its contents to the display surface. Additionally, the view automatically redraws the affected part of the image to reflect those changes, when the model changes. There can be multiple views onto the same model and each of these views can render the contents of the model to a different display surface.

View is designed to be nested. A view may be a composite view containing several sub-views, which may themselves contain several sub-views. As a matter of fact, most windows in fact involve at least two views, one nested inside the other.

\subsection{Controller}

Controller is responsible for taking the inputs from users and instructing Model and View to perform actions based on the inputs. The purpose of Controller is to act as a dispatcher. It chooses the right model and the corresponding view, then the request from users can be handled by the right business logic and the results can be displayed on the GUI front-end representing the view. Controller does not process the data. For example, when a user clicks a button, the controller accepts the request, then transfers the message to the model, tells the model what to do, and chooses the qualified view to return the results to the user. Therefore, it makes sense that a model can be mapped to several views, and a view can be mapped to several models as well. 

\subsection{How They Work}

\begin{figure}
	\centering
		\includegraphics[width=1.00\textwidth]{../pic/MVC.jpg}
	\caption{Communication Among The Model, View and Controller}
	\label{fig:MVC}
\end{figure}

Figure \ref{fig:MVC} shows the communication among Model, View and Controller. In this figure, Model points to View, which allows it to send View event notifications of change. Of course, Model's pointer to View is only a base class pointer; the model should know nothing about the kind of Views which observe it. By contrast, View knows exactly what kind of Model it observes. View also has a solid-line pointer to Model, allowing it to call any of Model's functions, e.g. state query. In addition, View also has a pointer to Controller, but it should not call functions in Controller aside from those defined in the base class. The reason is one controller may need to be swapped out for another, so the dependencies should be kept minimal. Controller has pointers to both Model and View and knows the type of both. Since Controller defines the behavior of the triad, it must know the type of both Model and View in order to translate user input into application response.

\subsubsection{A Concrete Example}

Here MVC pattern is explained with the help of a simple spinner component which consists of a text field and two arrow buttons that can be used to increment or decrement a numeric value shown in the text field. Currently there is not an element type that can directly represent a spinner component, but it easy is to synthesize a spinner using existing element types. Figure \ref{fig:spinnerMVC} illustrates the spinner in terms of MVC.

The spinner's data is held in a model that is shared with the text field. The text field provides a view of the spinner's current value. Each button in the spinner is an event source that spawns an action event every time it is clicked. The buttons can be hooked up to trampolines that receive action events, and route them to an action listener that eventually handles that event. Recall that a trampoline is a predefined action listener that simply delegates action handling to another listener.

Depending on the source of the event, the ultimate action listener either increments or decrements the value held in the model. As a matter of fact, the action listener is an example of a controller.

The trampolines, which initially receive the action events fired by the arrow buttons, are also controllers. However, instead of modifying the spinner's model directly, they delegate the task to a separate controller.

\begin{figure}
	\centering
		\includegraphics{../pic/spinnerMVC.jpg}
	\caption{A Spinner Example}
	\label{fig:spinnerMVC}
\end{figure}


\subsection{Advantages and Disadvantages}

Most of the procedure programming languages adopt the mixed programming model. They don't separate the data, the business logic and user interface, or at least there is only a little effort put on such separation. Therefore, even though the development can be done fast, but because of the mixed structure, the flexibility and maintenance are quite challenged. It is fairly different to meet the changing requirements from the customers. However, MVC insists on making the clear division of these three modules. Although it takes extra work, the whole structure is much clearer, and any change in the future can also be easily taken care of. 

\subsubsection{Advantages}

\begin{itemize}
	\item It has the capability of mapping several views to one model. In the case that the customers change the ideas quite often, they might have the demand of having various possibilities to access the application. For example, users can book a flight ticket via a desktop application, in the website over Internet or in whatever other ways, but the process for reserving a ticket is the same. In the MVC pattern, mapping several views of booking tickets to one model of accepting the booking requests and making the reservations is enough to meet the need. By this means, it avoids the code duplications, minimize the code maintenance. Once the model needs to be changed, it does not break the views.
	\item Because one application is divided into three parts, sometimes changing one of them can just meet the changed requirements. For example, only the model part should be changed if some business logic needs to be changed or new business logic needs to be added.
	\item It is better for the software engineering management. Since different modules take care of their own tasks, and the applications in each of the modules share some common features, it supplies the possibility to generate the management code in the manner of engineering.
\end{itemize}

\subsubsection{Disadvantages}

\begin{itemize}
	\item It increases the complexity of the system's structure and according implementation. For the simple user interface, strictly complying with MVC and separating the model, the view and the controller just involves a lot more code, and decrease the working efficiency accordingly. 
	\item The dependency between View and Controller is too tight. They are indeed separate, but functionally reply on each other very much. View without Controller has much less meaning, so does Controller without View. This prevents the reusability of any of the both alone.
	\item View accesses the data from Model with lower efficiency. To retrieve the complete data to display, View might need to make several calls to Model. During the calls, the unchanged data probably has to be retrieved again. If the mount of the data is fairly big, this can greatly lower down the performance.   
\end{itemize}
